﻿define(['jquery', 'underscore', 'sammy', 'config', 'presenter'], function($, _, Sammy, config, presenter) {
	var defaultRoute = '', startupUrl = '', logger = config.logger, currentHash = '', notNavigate, sammy = new Sammy.Application(function() {
		if (Sammy.Title) {
			this.use(Sammy.Title);
			this.setTitle(config.title);
		}
	}), register = function(options) {
		if (options.routes) {
			// Register a list of routes
			_.each(options.routes, function(route) {
				registerRoute({
					role : route.role,
					route : route.route,
					title : route.title,
					callback : route.callback,
					isDefault : !!route.isDefault,
					view : options.view,
					group : route.group
				});
			});
			return;
		}

		// Register route
		registerRoute(options);
	}, registerRoute = function(options) {
		if (!options.callback) {
			throw Error('callback must be specified.');
		}

		if (options.isDefault) {
			defaultRoute = options.route;
		}

		sammy.get(options.route, function(context) {
			currentHash = this.app.getLocation();
			var role = options.role;
			//reset overlay
			if (!options.view) {
				logger.error(config.toasts.invalidRoute);
				presenter.toggleActivity(false);
				return false;
			}
			options.callback(context.params);
			// Activate the viewmodel
			$('.view').hide();
			presenter.transitionTo($(options.view), window.location.hash, options.group);
			if (this.title) {
				this.title(options.title);
			}
		});
	}, run = function() {
		// 1) if i browse to a location, use it
		startupUrl = defaultRoute;

		if (!startupUrl) {
			logger.error('No route was indicated.');
			return;
		}
		sammy.run(startupUrl);
	}, navigateTo = function(url){
		sammy.setLocation(url);
	};

	return {
		register : register,
		run : run,
		navigateTo: navigateTo
	};
}); 